package controllers.manage.product;

import controllers.BaseController;
import controllers.auth.Secure;
import helper.GlobalConfig;
import jodd.util.StringUtil;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;
import product.type.ProductType;

import java.util.HashMap;
import java.util.Map;

/**
 * 产品类别管理
 * Created by hanbin on 17/4/6.
 */
@With(BaseController.class)
public class ProductTypeCtrl extends Controller{

    /**
     * 跳转到产品类别管理页面
     */
    public static void index(Integer pageNumber, String name){

        Merchant merchant = Secure.getLoginUser().merchant;

        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();

        if(StringUtil.isNotBlank(name)) {
            searchMap.put("name", "%"+name+"%");
        }

        if(merchant != null){
            searchMap.put("merchantId", merchant.id);
        }

        flash.put("menuId", "13");

        JPAExtPaginator<ProductType> resultPage = ProductType.findByCondition(searchMap, "sort desc", pageNumber, GlobalConfig.PAGE_SIZE);
        render(resultPage, pageNumber, name);
    }

    /**
     * 跳转到新增产品类别页面
     */
    public static void add(){
        render();
    }

    /**
     * 跳转到修改产品类别页面
     */
    public static void modify(long id, Integer pageNumber){
        ProductType productType = ProductType.findById(id);
        render(productType, pageNumber);
    }


    /**
     * 创建产品类别
     */
    public static void create(ProductType productType){

        Merchant merchant = Secure.getLoginUser().merchant;
        productType.merchant = merchant;

        productType.deleted = DeletedStatus.UN_DELETED;
        productType.save();
        flash.put("msg" , "产品类别创建成功");
        redirect("/BS0018/admin/product/type/index/1");
    }

    /**
     * 修改产品类别
     */
    public static void update(Long id, ProductType productType, Integer pageNumber){
        ProductType.update(id, productType);
        flash.put("msg" , "产品类别修改成功");
        redirect("/BS0018/admin/product/type/index/"+pageNumber);
    }

    /**
     * 删除产品类别
     */
    public static void delete(long id , Integer pageNumber){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        ProductType productType = ProductType.findById(id);
        //判断产品类型是否被使用
        if(ProductType.checkIsUsed(id)){
            flash.put("msg" , "该产品类别正在被使用,无法删除!");
            redirect("/BS0018/admin/product/type/index/"+pageNumber);
        }

        productType.deleted=DeletedStatus.DELETED;
        productType.save();
        flash.put("msg" , "产品类别删除成功");
        redirect("/BS0018/admin/product/type/index/"+pageNumber);
    }

}
